<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="com.data.ConnData" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>题目详细内容及代码编辑器</title>
    <!-- 引入CodeMirror的样式文件 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.62.0/codemirror.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.62.0/theme/monokai.css">
    <!-- 引入monokai主题样式 -->
    <link rel="stylesheet" href="../css/oj.css">
</head>
<body>
<div class="container">
    <!-- 左侧题目信息区域 -->
    <div class="left-panel">
        <%
            request.setCharacterEncoding("utf-8");
            String questionId = request.getParameter("question_id");

            ConnData objdata = new ConnData();
            Connection connection = null;
            PreparedStatement psmt = null;
            ResultSet resultSet = null;
            try {
                connection = objdata.getConn();
                // 根据传入的题目ID查询题目详细信息的SQL语句，这里查询所有字段，你可按需调整
                String sql = "SELECT * FROM question_table WHERE question_id =?";
                psmt = objdata.getPsmt(sql);
                psmt.setString(1, questionId);
                resultSet = psmt.executeQuery();
                if (resultSet.next()) {
        %>
        <h2><%=resultSet.getString("question_name")%>
        </h2>
        <p><strong>题目内容：</strong><br><%=resultSet.getString("question_content")%>
        </p>
        <p><strong>样例输入：</strong><br><%=resultSet.getString("sample_input")%>
        </p>
        <p><strong>样例输出：</strong><br><%=resultSet.getString("sample_output")%>
        </p>
        <input type="hidden" value="<%=resultSet.getString("test_case_input")%>" name="input" id="input">
        <input type="hidden" value="<%=resultSet.getString("test_case_output")%>" name="output" id="output">

        <%
            psmt.close();
            objdata.close();
        } else {
        %>
        <p>未找到该题目的详细信息，请检查题目ID是否正确。</p>
        <%
            }
        } catch (SQLException e) {
            e.printStackTrace();
        %>
        <p>数据库操作出现错误，请稍后再试！</p>
        <%
            } finally {
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (psmt != null) {
                    try {
                        psmt.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        %>
    </div>
    <!-- 右侧代码编辑与运行相关区域 -->
    <div class="right-panel">
        <div id="editor"></div>

        <div style="display: flex; justify-content: space-between; align-items: center; padding: 5px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border-radius: 3px;">
            <a href="question.jsp"
               style="margin-left: 5px; text-decoration: none; color: white; background-color: #007bff; padding: 5px 10px; border: none; border-radius: 3px; text-align: center; font-size: 12px; cursor: pointer; transition: background-color 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);"
               onmouseover="this.style.boxShadow='0 2px 4px rgba(0, 0, 0, 0.2)'"
               onmouseout="this.style.boxShadow='0 1px 2px rgba(0, 0, 0, 0.1)'">
                返回
            </a>
            <button class="btn btn-success" id="submitButton"
                    style="margin-right: 5px; background-color: #28a745; color: white; padding: 5px 10px; border: none; border-radius: 3px; font-size: 12px; cursor: pointer; transition: background-color 0.3s ease, box-shadow 0.3s ease; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);"
                    onmouseover="this.style.boxShadow='0 2px 4px rgba(0, 0, 0, 0.2)'"
                    onmouseout="this.style.boxShadow='0 1px 2px rgba(0, 0, 0, 0.1)'">
                提交代码
            </button>
        </div>

        <div id="resultArea"></div>
    </div>
</div>
<%!
    int right = 0;
%>
<!-- 引入CodeMirror的脚本文件 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.62.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.62.0/mode/python/python.js"></script>
<!-- 引入Python语言模式支持脚本 -->
<script>
    window.onload = function () {
        // 初始化CodeMirror代码编辑器，设置为Python语言模式等属性，并应用monokai主题，确保代码高亮，同时设置字号
        var editor = CodeMirror(document.getElementById("editor"), {
            mode: "python",
            lineNumbers: true,
            theme: "monokai",
            indentUnit: 4,
            autofocus: true,
            extraKeys: {
                "Ctrl-Space": "autocomplete",
            },
            styleActiveLine: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            foldGutter: true,
            lineWrapping: true,
            fontFamily: "微软雅黑",
            fontSize: 18,
            height: "800px"
        });

        var submitButton = document.getElementById("submitButton");
        var resultArea = document.getElementById("resultArea");
        var input = document.getElementById("input");
        var output = document.getElementById("output");

        submitButton.addEventListener('click', function () {
            var code = editor.getValue(); // 使用CodeMirror提供的方法获取代码内容，更准确
            var testInput = input.value;
            var rs = output.value;
            code = code.replace(/^\d+\.?\s?/gm, "");
            console.log(code);
            fetch('http://localhost:8000/execute_code', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({"code": code, "input": testInput})
            })
                .then(response => response.json())
                .then(data => {
                    if (data.message === "代码运行成功") {
                        <%
                            right=1;
                        %>
                        console.log(data.execution_time);
                        var res = String(data.result);
                        var r = String(rs);
                        res = res.trim()
                        if (res != null) {
                            if (res == r) {
                                console.log(res);
                                console.log(r);
                                resultArea.innerHTML = "Accept" + "<br>运行时间<br>" + data.execution_time + "ms<br>占用内存<br>" + data.memory_usage;
                            } else {
                                resultArea.innerHTML = "Wrong" + "<br>运行时间<br>" + data.execution_time + "ms<br>占用内存<br>" + data.memory_usage;
                            }
                            console.log("运行结果");
                            console.log(data.result);
                            console.log(rs);
                        } else {
                            resultArea.innerHTML = "代码运行出错<br>" + "<br>运行时间<br>" + data.execution_time + "ms<br>占用内存<br>" + data.memory_usage;
                        }

                    } else {
                        resultArea.innerHTML = `代码运行出错：<br>${data.error}`;
                    }
                })
                .catch(error => {
                    console.error("出现错误：", error);
                    resultArea.innerHTML = "出现未知错误，请稍后再试";
                });
    <%
    ConnData obj = new ConnData();
    Connection conn = null;
    PreparedStatement p = null;
    int rs = 0;
    try {
    conn = obj.getConn();
    String getSessionUser=(String)session.getAttribute("sess_user");

    String sql = "INSERT INTO user_answer_table(user_id, question_id, answer_status) SELECT ID,?,?  FROM user_table  WHERE nickname =?";
    p = obj.getPsmt(sql);
    p.setString(1, questionId);
    p.setString(2, String.valueOf(right));
    p.setString(3, getSessionUser);
    rs = p.executeUpdate();
    if(rs==1){
         p.close();
         obj.close();
    }
    } catch (Exception e) {}
    %>
        });
    };
</script>
</body>
</html>